<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

class authorize extends JObject {         
	var $ipn_data = array();         
	var $config;  
	protected   $x_version ='3.1';
	protected   $x_login;
	protected   $x_receipt_link_url;
	protected   $x_relay_url;
	protected   $secret_word;
   	function __construct($config) { 
   		if (!isset($config->x_login))   	  
   		{
			$config->x_version = '';
   			$config->tkey = '';
   			$config->secret_word = '';
   			$config->x_receipt_link_url = '';
   			$config->title = '';
   			$config->currency = '';
   			$config->x_relay_url = '';
   			$config->server='';
   		}
      $this->config = $config;
   	}
      	
	function config_form(){
		global $mainframe, $option;
		/* Fill in the config tag below. Note that need not write the form */
		?>	
		<script type="text/javascript">
			function change_receipt_option(a)
			{
				if(a=='true')
				{
					$('for_relay_response').setStyle('display','');
					$('for_receipt_link_url').setStyle('display','none');
					$('for_receipt_link_text').setStyle('display','none');
				}
				else
				{
					$('for_relay_response').setStyle('display','none');
					$('for_receipt_link_url').setStyle('display','');
					$('for_receipt_link_text').setStyle('display','');
				}
			}
		</script>
		<tbody><tr>
			    <td class="key"><?php echo JText::_('Authorize.Net API Login ID');?></td>
			    <td>
			             <input name="authorize[x_login]" value="<?php echo @$this->config->x_login?>" size="30" maxlength="255" type="text">
			     </td>
			</tr>
			<tr>
			    <td class="key">
				    <?php echo JText::_('Transaction Key')?>
				</td>
			    <td>
			         <input name="authorize[tkey]" value="<?php echo @$this->config->tkey?>" size="30" maxlength="255" type="text">
			         <br><small> <?php echo JText::_('The transaction key is generated by the system 
				    and can be obtained from Merchant Interface.    To obtain the transaction key from the Merchant Interface');?>
			         <ol>
			         	<li><?php echo JText::_('Log into the Merchant Interface')?></li>
			         	<li><?php echo JText::_('Select Settings from the Main Menu')?></li>
			         	<li><?php echo JText::_('Click on Obtain Transaction Key in the Security section')?></li>
			         	<li><?php echo JText::_('Type in the answer to the secret question configured on setup')?></li>
			         	<li><?php echo JText::_('Click Submit')?></li>
			         </ol>
					</small>
			    </td>
			</tr>
			<tr>
			    <td class="key"><?php echo JText::_('Secret Word');?></td>
			    <td>
			             <input name="authorize[secret_word]" value="<?php echo @$this->config->secret_word?>" size="30" maxlength="255" type="text">
			             <br /><small> <?php echo JText::_('From authorize.net MD5 Hash menu. You have to create secret word');?></small>
			    </td>
			</tr>
			<tr>
			    <td class="key"><?php echo JText::_('Test Mode Enabled');?></td>
			    <td><select name="authorize[testing]" size="1">
			            <option value="0">No</option>
			            <option value="1">Yes </option>
			         </select>
			         <br><small> <?php echo JText::_('set to No after you complete testing');?></small>
			    </td>
			</tr>
			<tr>
		      <td class="key"><?php echo JText::_('Gateway URL');?></td>
		      <td>
		      	  <input size="90" type="text" value="<?php echo $this->config->server; ?>" name="authorize[server]" />
		      	  <br/> <small><?php echo JText::_('Recommended')?>: 
		      	  	<ol>
		      	  		<li><?php echo JText::_('Test mode') ?>:  https://test.authorize.net/gateway/transact.dll</li>
		      	  		<li><?php echo JText::_('Live mode') ?>:  https://secure.authorize.net/gateway/transact.dll</li>
		      	  	</ol>
		      	  </small>
		      	  
		      </td>
		    </tr>
			<tr>
			    <td class="key"><?php echo JText::_('Receipt Options');?></td>
			    <td><select name="authorize[x_relay_response]" size="1" onchange="change_receipt_option(this.value);">
			            <option value="true"><?php echo JText::_('Relay Response')?></option>
			            <option value="false"><?php echo JText::_('The Receipt Page')?> </option>
			         </select>
			    </td>
			</tr>
		    <tr id="for_relay_response" <?php if (isset($this->config->x_relay_response)&&!($this->config->x_relay_response)) echo "style=\"display:none\"";?> >
		      <td class="key"><?php echo JText::_('Relay URL');?></td>
		      <td>
			      <input type="text" name="authorize[x_relay_url]" size="90" value="<?php echo $this->config->x_relay_url; ?>"><br>
			      <small><?php echo JText::_('Enter the return URL here. The return URL for should be: '); ?>: <b><?php echo JRoute::_(JURI::root()."index.php?option=$option&view=japayment&task=payment_notify&payment_method=".$this->config->name); ?></b> <br/>
				  	 	<?php echo JText::_("This setting overwrites the 'Relay Response' URL set in your authorize.net merchant account")?></small>
		      </td>
		    </tr>
		    <tr id="for_receipt_link_url" <?php if (!isset($this->config->x_relay_response)||($this->config->x_relay_response)) echo "style=\"display:none\"";?>>
		      <td class="key"><?php echo JText::_('Receipt URL');?></td>
		      <td>
			      <input type="text" name="authorize[x_receipt_link_url]" size="90" value="<?php echo $this->config->x_receipt_link_url; ?>"><br />
			      <small><?php echo JText::_("The URL of the link that directs the customer back to your website")?></small>
		      </td>
		    </tr>
		    <tr id="for_receipt_link_text" <?php if (!isset($this->config->x_relay_response)||($this->config->x_relay_response)) echo "style=\"display:none\"";?>>
		      <td class="key"><?php echo JText::_('Receipt hyperlinked text');?></td>
		      <td>
			      <input type="text" name="authorize[x_receipt_link_text]" size="50" value="<?php echo $this->config->x_receipt_link_text; ?>">
		      </td>
		    </tr>
		</tbody>		    
		<input name="name" value="authorize" type="hidden">	  		
		<?php
	}
	
	function more_info(){
		
	}		
   
	/**
	* Process notification post from paypal
	*
	*/
	function check_payment(){
		
		//Get 2Checkout config
		$db	= JFactory::getDBO();
		$query = "SELECT * FROM #__ja_paymentconfig WHERE name='authorize'";
		$db->setQuery($query);
		$payment = $db->loadObject();
		$payment->datas = new JParameter($payment->datas);
		
		global $jbconfig, $mainframe;
		$postipn = $this->toParamsString($_POST);
//		if (JRequest::getVar('merchant_id')!='') { 

			$merchant_id = JRequest::getVar('merchant_id');
			$transaction_id = JRequest::getVar('transaction_id');
			$secret = strtoupper(md5($payment->datas->get('secret_word')));
			$mb_amount = JRequest::getVar('mb_amount');
			$mb_currency = JRequest::getVar('currency');
			$status = JRequest::getVar('status');
			$md5sig = JRequest::getVar('md5sig');
			$product_type = substr($transaction_id, 0, 1);// 'P' or 'S'
			$txn_id = JRequest::getVar('mb_transaction_id');
			$invoice_id = substr($transaction_id, 1);			
			$working_sig = strtoupper (md5($merchant_id.$transaction_id.$secret.$mb_amount.$mb_currency.$status));

			if (strcmp($working_sig, $md5sig )==0) {
				$sql="SELECT count(*) FROM #__ja_transactions WHERE txn_id='$txn_id'";
				$db->setQuery($sql);
				$total = $db->loadResult();
				if($total){
					return false;
				}
				else{
					$db->setQuery("SELECT * FROM #__ja_transactions WHERE id = ".(int)$invoice_id.";");
					$ret = $db->loadObject();
					$ret->txn_id = $txn_id;
					switch ($status) {
						case "-2":
							break;
						case "2":
							$ret->completed = 1;
							$ret->datas = $this->ipn_data;
							return $ret;
							break;
						case "1": // scheduled (wait for 2 or -2)
							$ret->completed = 0;
							$ret->datas = $this->ipn_data;
							return $ret;
							break;
						case "0": // pending	
						case "-1": // cancelled
							$ret->datas = $this->ipn_data;
							$ret->completed = 0;
							return $ret;
							break;
					}
					return false;
					
				}

			} else {
					return false;
			}

//		}
//		else 
//		 return false;		

	}
	
	function toParamsString($vars){
		$postipn = "";
		foreach ($vars as $ipnkey => $ipnval)
		{
			$this->ipn_data["$ipnkey"] = $ipnval;
			$postipn.='&'.@$ipnkey.'='.urlencode(@$ipnval); 
		} // Notify string
		return $postipn;
	}
	

	
	function payment_return() {
		$db	= JFactory::getDBO();
		$query = "SELECT * FROM #__ja_paymentconfig WHERE name='authorize'";
		$db->setQuery($query);
		$payment = $db->loadObject();
		$payment->datas = new JParameter($payment->datas);
		
		global $jbconfig, $mainframe;
		$invoice    = JRequest::getVar('x_invoice_num');
		$pnref      = JRequest::getVar('x_trans_id');
		$amount     = doubleval(JRequest::getFloat('x_amount'));
		$result     = JRequest::getVar('x_response_code');
		$respmsg    = JRequest::getVar('x_response_reason_text');
		if ($result != 1){
		     JError::raiseError(500,$respmsg);
		     return false;
		}
		if (!$amount){
		      JError::raiseError(501,JText::_('PAY_AUTHORIZE_USER_ERR'));
		      return false;
		}
		$secret = strtoupper(md5($payment->datas->get('secret_word')));
		$md5source =$secret . $payment->datas->x_login. $vars['x_trans_id'] . $vars['x_amount'];
		$md5 = md5($md5source);
		if (strtoupper($md5) != JRequest::getVar('x_MD5_Hash')){
		     JError::raiseError(502,JText::_('This payment is not authorize'));
		     return false;
		}
		if (!$pnref && !$payment->datas->get('testing'))
		{
		    JError::raiseError(503,JText::_('Response is invalid'));
		    return false;
		}
		if ($invoice!='')
		{
			    $query = "SELECT * FROM #__ja_transactions WHERE id=".(int)substr($invoice,1);
				$db->setQuery($query);
				$ret = $db->loadObject();
				if (!$ret->txn_id)
				{
					$ret->txn_id = $pnref;
					$ret->completed = 1;
//					$db->setQuery("UPDATE #__ja_transactions SET completed=1,txn_id='$msid' WHERE id=".substr($transaction_id,1));
//					$db->query();
					return $ret;
				}
				?>
				<div id="Mod18" class="jamod module">
				<div>
				<div>
					<div>
					
						<div class="jamod-content" style="overflow: hidden;">
							<?php echo JText::_("Your moneybooker payment has been completed successfully.")?><br/>
							<?php echo JText::_("You will receive an email with information about the status of your transaction within minutes.")?><br/>
							<?php echo JText::_("If you do not receive the email within 20 minutes, please <b>contact us</b>.")?><br/>
						</div>
					</div>
				</div>
				</div>
				</div>
				
				<?php	
						$ret = new stdClass();
						return $ret;
		}
		else 
		{
			return false;
		}
			
	}
	
	function payment_cancel() {
		JError::raiseNotice(1,JText::_("You hvae cancelled the moneybooker payment or the payment was not completed."));
		JError::raiseNotice(1,JText::_("Please feel free to contact us if your experience was not as it should be."));
	}
	
	function assign_params($vars,$values,$payment)
	{
		$vars['x_version']   = '3.0';
        $vars['x_test_request'] = $payment->config->testing? 'TRUE' : 'FALSE';
        unset($vars['testing']);
        $vars['x_show_form'] = 'PAYMENT_FORM';
        $vars['x_amount']    = $values['amount'] = sprintf('%.2f', $values['amount']);
        $relay_response = $payment->config->x_relay_response;
        if ($relay_response)
        {
        	$vars['x_relay_response'] = 'TRUE';
        	$vars['x_relay_url']   = $payment->config->x_relay_url; 
        	unset($vars['x_receipt_link_url']);
        	unset($vars['x_receipt_link_text']);
        }
        else 
        {
        	$vars['x_receipt_link_url'] =$payment->config->x_receipt_link_url;
        	$vars['x_receipt_link_url'] =$payment->config->x_receipt_link_text;
        	unset($vars['x_relay_response']);
        	unset($vars['x_relay_url']);
        }
           // $config['root_url'] . '/thanks.php',
        $vars['x_invoice_num']   =$values['item_number'];
        $vars['x_cust_id']       =$values['member_id'];
        $vars['x_description']   = $payment->config->title;
        $vars['x_delim_data']   = false;
        $vars['x_type']   = 'CREDIT';
        $vars['x_fp_sequence'] = $values['item_number'];
        $vars['x_fp_timestamp'] = $tstamp = time();
        $data = $payment->config->x_login."^".$values['item_number']."^".$tstamp."^".$values['amount']."^";
        $vars['x_fp_hash'] = $this->hmac($payment->config->tkey, $data);
        foreach ($vars as $kk=>$vv){
            $v = urlencode($vv);
            $k = urlencode($kk);
            $vars1[$k] = "$v";
         //   echo strtolower($k); echo "<br/>";
        }
        unset($vars1['tkey']);
        unset($vars1['secret_word']);
       /*  $vars2 = join('&', $vars1);
        header("Location:https://test.authorize.net/gateway/transact.dll?$vars2");
        exit();*/
      /*	var_dump($vars);
      	exit;*/
		return $vars1;
		
	}
	function hmac ($key, $data)
    {
       // RFC 2104 HMAC implementation for php.
       // Creates an md5 HMAC.
       // Eliminates the need to install mhash to compute a HMAC
       // Hacked by Lance Rushing

      /* $b = 64; // byte length for md5
       if (strlen($key) > $b) {
           $key = pack("H*",md5($key));
       }
       $key  = str_pad($key, $b, chr(0x00));
       $ipad = str_pad('', $b, chr(0x36));
       $opad = str_pad('', $b, chr(0x5c));
       $k_ipad = $key ^ $ipad ;
       $k_opad = $key ^ $opad;

       return md5($k_opad  . pack("H*",md5($k_ipad . $data)));*/
      if( phpversion() >= '5.1.2' )
		{	
			$fingerprint = hash_hmac("md5", $data, $key); }
		else 
		{ $fingerprint = bin2hex(mhash(MHASH_MD5, $data, $key)); }
		return $fingerprint;
    }
	
}
?>